import dayjs from "dayjs";
/**
 * @param { string | number } time
 * @param { string } cFormat 输出时间字符串格式 默认 '{y}-{m}-{d} {h}:{i}:{s}'
 * @returns { string | null } 格式化后的时间字符串, 如果传入的时间参数为空则返回 null
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) return null;

  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^\d+$/.test(time))
        // support "1548221490638"
        time = Number.parseInt(time);
      // support safari
      // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
      else time = time.replace(/-/g, "/");
    }

    if (typeof time === "number" && time.toString().length === 10)
      time = time * 1000;

    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/\{([ymdhisa])+\}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") return ["日", "一", "二", "三", "四", "五", "六"][value];

    return value.toString().padStart(2, "0");
  });
  return time_str;
}
/**
 * 统一修改 option 键值
 * @param {*} list 数组
 * @param {*} param1 value=后台返回的value, label=后台返回的label
 * @returns
 */
export function formatOptions(list, { value = "id", label = "name" } = {}) {
  return list?.map(item => ({
    ...item,
    value: item[value],
    label: item[label]
  }));
}
/**
 * 输入处理工具
 * @param value 输入值
 * @param type 处理类型
 * @returns 处理后的值
 */
export function handleInput(
  value: string,
  type: "numberAndLetter" | "number" | "letter" = "numberAndLetter"
) {
  if (!value) return "";
  const handlers = {
    // 只能输入数字和字母
    numberAndLetter: () => value.replace(/[^a-zA-Z0-9]/g, ""),
    // 只能输入数字
    number: () => value.replace(/[^\d]/g, ""),
    // 只能输入字母
    letter: () => value.replace(/[^a-zA-Z]/g, "")
  };
  return handlers[type]();
}
/**
 * 检查时间
 * @param param0
 * @returns
 */
export function checkTime(
  createTime: string,
  op: ">" | "<" | ">=" | "<=" | "==",
  target: number
): boolean {
  if (!createTime) return null;
  // 当前时间
  const currentTime = dayjs();
  // 转换创建时间为 dayjs 对象
  const createTimeDate = dayjs(createTime, "YYYY-MM-DD HH:mm:ss");
  // 计算当前时间与创建时间的时间差，单位为分钟
  const diffInMinutes = currentTime.diff(createTimeDate, "minute");
  // 根据比较操作符进行判断
  switch (op) {
    case ">":
      return diffInMinutes > target;
    case "<":
      return diffInMinutes < target;
    case ">=":
      return diffInMinutes >= target;
    case "<=":
      return diffInMinutes <= target;
    case "==":
      return diffInMinutes === target;
    default:
      throw new Error("无效的操作符。请使用 '>', '<', '>=', '<=' 或 '=='");
  }
}
/**
 * 获取两个日期之间的所有日期
 * @param start 开始时间
 * @param end 结束时间
 * @returns Array
 */
export function getDateRange(start: string, end: string) {
  const startDate = dayjs(start);
  const endDate = dayjs(end);
  const dates = [];

  // 循环获取日期
  let currentDate = startDate;
  while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, "day")) {
    dates.push(currentDate.format("YYYY-MM-DD"));
    currentDate = currentDate.add(1, "day");
  }
  return dates;
}
/**
 * 生成随机字符串
 */
export function generateRandomString(length: number) {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
/**
 * 获取当前时间的开始或结束时间
 * 23:59:59 - 00:00:00
 */
export function getDayTime(time: string, type = "start") {
  if (!time) return null;
  if (type === "end") return dayjs(time).format("YYYY-MM-DD 23:59:59");
  return dayjs(time).format("YYYY-MM-DD 00:00:00");
}
/**
 * 搜索的开始、结束时间格式化
 */
export function formatTime(value, type = "start") {
  if (type === "start") {
    return dayjs(value)
      .endOf("day")
      .subtract(0, "second")
      .format("YYYY-MM-DD HH:mm:ss");
  }
  return dayjs(value).endOf("day").format("YYYY-MM-DD HH:mm:ss");
}
